package com.tools.web.interceptor.access.spel;

import com.tools.common.object.Note;
import com.tools.web.GlobalKit;
import com.tools.web.interceptor.auth.AuthUser;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * 授权检查的处理器对象
 * */
@Note("授权检查的处理器对象")
public class AuthorizeHandler extends GenericParamValidHandler {

    public AuthorizeHandler() {}

    /* *****************************************************************************************
     *
     *      功能方法
     *
     * *****************************************************************************************
     * */

    @Note("用户必须拥有 roleIds 的所有角色才返回 true")
    public final boolean hasAllRole(HttpServletRequest request, String[] roleKeys) {
        Map<String, ?> roleKeyMap = this.protected_getRoleSet(request);
        for (String roleKey : roleKeys) {
            if (!roleKeyMap.containsKey(roleKey)) return false;
        }
        return true;
    }

    @Note("用户只需要拥有 roleIds 中的任意一个角色就返回 true")
    public final boolean hasAnyRole(HttpServletRequest request, String[] roleKeys) {
        Map<String, ?> roleKeyMap = this.protected_getRoleSet(request);
        for (String roleKey : roleKeys) {
            if (roleKeyMap.containsKey(roleKey)) return true;
        }
        return false;
    }


    @Note("用户必须拥有 permIds 的所有权限才返回 true")
    public final boolean hasAllPerm(HttpServletRequest request, String[] permKeys) {
        Map<String, ?> permissionKeyMap = this.protected_getPermissionSet(request);
        for (String permKey : permKeys) {
            if (!permissionKeyMap.containsKey(permKey)) return false;
        }
        return true;
    }


    @Note("用户只需要拥有 permIds 中的任意一个权限就返回 true")
    public final boolean hasAnyPerm(HttpServletRequest request, String[] permKeys) {
        Map<String, ?> permissionKeyMap = this.protected_getPermissionSet(request);
        for (String permKey : permKeys) {
            if (permissionKeyMap.containsKey(permKey)) return true;
        }
        return false;
    }


    /* *****************************************************************************************
     *
     *      私有逻辑
     *
     * *****************************************************************************************
     * */


    @Note("获取用户的角色集合")
    protected Map<String, ?> protected_getRoleSet(HttpServletRequest request) {
        AuthUser authUser = GlobalKit.getAuthUser(request);
        return authUser.getRoleKeyMap();
    }

    @Note("获取用户的权限集合")
    protected Map<String, ?> protected_getPermissionSet(HttpServletRequest request) {
        AuthUser authUser = GlobalKit.getAuthUser(request);
        return authUser.getPermissionKeyMap();
    }


}
